﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NBusiness.Data.Providers.SqlServer.Query;
using System.Reflection;

namespace NBusiness.Query.Testing
{
    [TestClass]
    class SqlContextTests
    {
        [TestMethod]
        public void SqlContextTest1()
        {
            SqlQueryContext context = new SqlQueryContext();
            MethodInfo getNextAlias = typeof(SqlQueryContext).GetMethod("GetNextAlias", BindingFlags.NonPublic | BindingFlags.Instance);

            string[] expected = new string[]{
                "A", "B", "C", "D", "E", "F", "G", "H", "I", 
                "J", "K", "L", "M", "N", "O", "P", "Q", "R",
                "S", "T", "U", "V", "W", "X", "Y", "Z",
                "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI",
                "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR",
                "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ",
                "CA", "CB"};


            for (uint x = 0; x < expected.Length; x++)
            {
                string actual = (string)getNextAlias.Invoke(context, null);
                Assert.AreEqual(expected[x], actual);
            }
        }

        [TestMethod]
        public void SqlContextTest2()
        {
            SqlQueryContext context = new SqlQueryContext();
            MethodInfo getNextAlias = typeof(SqlQueryContext).GetMethod("GetNextAlias", BindingFlags.NonPublic | BindingFlags.Instance);

            string e1 = "BAAA";
            int n1 = 17576;

            for (uint x = 0; x <= n1; x++)
            {
                string actual = (string)getNextAlias.Invoke(context, null);
                if (x == n1)
                    Assert.AreEqual(e1, actual);
            }
        }

        [TestMethod]
        public void EnsureAliasUnique1()
        {
            ITable table = new SqlTable("A");

            string expected = "[A] AS [B]";
            string actual = table.ToSql();

            Assert.AreEqual(expected, actual);
        }

        [TestMethod]
        public void EnsureAliasUnique2()
        {
            ITable B = new SqlTable("B");
            ITable T = new SqlTable("T");
            IColumn C = new SqlColumn("C", B);
            IColumn D = new SqlColumn("D", T);

            ISelect select = new SqlSelect().From(B, T.InnerJoin(C.Equal(D)));

            string expected = "SELECT * FROM [B] AS [A] INNER JOIN [T] AS [C] ON ([A].[C]=[C].[D])";
            string actual = select.ToSql();

            Assert.AreEqual(expected, actual);
        }
    }
}
